package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.compete;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteTenderExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetCompeteTenderVo;
import com.xiaoxu.intranetweb.util.SzResult;
import groovyjarjarpicocli.CommandLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;

@Component
public class CompeteTenderBu {
    @Autowired
    private ITCompeteTenderService tCompeteTenderService;
    @Autowired
    private ICProductsInfoService iCProductsInfoService;
    @Autowired
    private ICCompanysService companysService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ITCompeteService competeService;
    @Autowired
    private ISysUserPlantConnService iSysUserPlantConnService;
    @Autowired
    private ITPlantsService iTPlantsService;
    @Autowired
    private ISysFilesService fileBu;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private ITCompeteDetailService tCompeteDetailService;
    @Autowired
    private ISysUserService iSysUserService;
    //新增竞标结果
    public SzResult addCompeteTender(String competeId, String PdtId, String price, String weight, String winBidPrice, String winBidWeight, String co, String chiCo, String status, String token,String plantId) throws Exception {
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        TCompeteTender competeTender = new TCompeteTender();
        QueryWrapper<TCompete> tCompeteQueryWrapper = new QueryWrapper<>();
        tCompeteQueryWrapper.eq("ID", competeId);
        tCompeteQueryWrapper.eq("DEL_FLAG", 0);
        tCompeteQueryWrapper.eq("DATA_FROM", plantId);
        TCompete tCompete = competeService.getOne(tCompeteQueryWrapper);
        if (tCompete == null) {
            return SzResult.error("竞标不存在");
        }

 /*       QueryWrapper<TCompeteTender> tCompeteTenderQueryWrapper = new QueryWrapper<>();
        tCompeteTenderQueryWrapper.eq("COMPETE_ID", competeId);
        tCompeteTenderQueryWrapper.eq("DEL_FLAG", 0);
        TCompeteTender tCompeteTender1 = tCompeteTenderService.getOne(tCompeteTenderQueryWrapper);
        if (tCompeteTender1 != null) {
            return SzResult.error("该竞标已有结果,请勿重复添加！");
        }*/
        competeTender.setCompeteId(competeId);
        QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", PdtId);
        queryWrapper.eq("PDTINF_DELETED", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper);
        if (cProductsInfo == null) {
            return SzResult.error("产品不存在");
        }


        QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("CPY_CO", co);
        queryWrapper1.eq("CPY_CHICO", chiCo);
        queryWrapper1.eq("CPY_PASS", 0);
        queryWrapper1.eq("CPY_TEMP_LOCK", 0);
        queryWrapper1.eq("CPY_DELETED", 0);
        queryWrapper1.eq("DATA_FROM", plantId);
        CCompanys company = companysService.getOne(queryWrapper1);
        if (company == null) {
            return SzResult.error("该单位不存在");
        }
        String id = company.getId();
        //查看该公司有没有投过该标
        QueryWrapper<TCompeteTender> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("CPY_ID", id);
        queryWrapper2.eq("PDT_ID", PdtId);
        queryWrapper2.eq("COMPETE_ID", competeId);
        queryWrapper2.eq("DEL_FLAG", 0);
        queryWrapper2.eq("DATA_FROM", plantId);
        TCompeteTender tCompeteTenderServiceById = tCompeteTenderService.getOne(queryWrapper2);
        if (tCompeteTenderServiceById != null) {
            return SzResult.error("该公司投过该标");
        }

        competeTender.setPdtId(PdtId);
        competeTender.setWinBid(status);

        if (price != null && !price.isEmpty()) {
            competeTender.setPrice(new BigDecimal(price));
        }
        if (weight != null && !weight.isEmpty()) {
            competeTender.setWeight(new BigDecimal(weight));
        }
        LocalDateTime CreatTime = LocalDateTime.now();
        competeTender.setCreateTime(CreatTime);

        if (status.equals("1")) {
            if (winBidPrice != null && !winBidPrice.isEmpty()) {
                competeTender.setWinBidPrice(new BigDecimal(winBidPrice));
            }
            if (winBidWeight != null && !winBidWeight.isEmpty()) {
                competeTender.setWinBidWeight(new BigDecimal(winBidWeight));
            }
        }


        competeTender.setCompeteAuditTime(LocalDateTime.now());
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        competeTender.setCompeteAuditorName(user.getTrueName());
        competeTender.setCompeteAuditor(user.getId());
        competeTender.setCpyId(id);
        competeTender.setDelFlag(0);
        competeTender.setDataFrom(plantId);//数据来源
        tCompeteTenderService.save(competeTender);
        //sysLogBu.logRecord("删除产品", user.getTrueName(), "删除了产品名称为" + pdtinfPdt + "的产品", userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId());
        String chineseStatus = null;
        if (status.equals("1")) {
            chineseStatus = "中标";
        } else if (status.equals("2")) {
            chineseStatus = "未中";
        }
        sysLogBu.logRecord("竞标结果", user.getTrueName(), "[手动录入]" + "录入了竞标结果:       竞标标题:" + tCompete.getTitle() + "        投标公司:" + co + "," + chiCo + "       产品:" + cProductsInfo.getPdtinfPdt() + "         价格（元）:" + price + "          重量（吨）:" + weight + "       是否中标:" + chineseStatus + "          中标单价:" + winBidPrice + "        中标总量:" + winBidWeight, plantId);
        return SzResult.Success();
    }

    //删除竞标结果
    public SzResult deleteCompeteTender(String id, String token,String plantId) throws Exception {
        QueryWrapper<TCompeteTender> tCompeteTenderQueryWrapper = new QueryWrapper<>();
        tCompeteTenderQueryWrapper.eq("ID", id);
        tCompeteTenderQueryWrapper.eq("DATA_FROM", plantId);
        TCompeteTender tCompeteTender = tCompeteTenderService.getOne(tCompeteTenderQueryWrapper);
        String competeId = tCompeteTender.getCompeteId();
        TCompete tCompete = competeService.getById(competeId);
        tCompeteTender.setDelFlag(1);
        tCompeteTenderService.updateById(tCompeteTender);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //sysLogBu.logRecord("撤销竞标信息", user1.getTrueName(), "撤销了【" + tCompete.getTitle() + "】的竞标信息", userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId());
        sysLogBu.logRecord("删除竞标结果", user1.getTrueName(), "删除了竞标结果:       竞标标题:" + tCompete.getTitle(), plantId);
        return SzResult.Success();
    }

    //修改竞标结果
    public SzResult updateCompeteTender(String id, String pdtId, String price, String weight,
                                        String winBidPrice, String winBidWeight, String winBid, String token,String plantId) throws Exception {


        QueryWrapper<TCompeteTender> tCompeteTenderQueryWrapper = new QueryWrapper<>();
        tCompeteTenderQueryWrapper.eq("ID", id);
        tCompeteTenderQueryWrapper.eq("DEL_FLAG", 0);
        tCompeteTenderQueryWrapper.eq("DATA_FROM", plantId);
        TCompeteTender tCompeteTender = tCompeteTenderService.getOne(tCompeteTenderQueryWrapper);
        String competeId = tCompeteTender.getCompeteId();
        QueryWrapper<TCompete> tCompeteQueryWrapper = new QueryWrapper<>();
        tCompeteQueryWrapper.eq("ID", competeId);
        tCompeteQueryWrapper.eq("DEL_FLAG", 0);
        tCompeteQueryWrapper.eq("DATA_FROM", plantId);
        TCompete tCompete = competeService.getOne(tCompeteQueryWrapper);
        if (tCompete == null) {
            return SzResult.Error("竞标不存在");
        }
        Integer status = tCompete.getStatus();
        //status在  51~60 定标 时，不能修改

        if (status >= 51 && status <= 60) {
            return SzResult.Error("已定标,不能修改");
        }
        if (status >= 31 && status <= 50 || status == 0) {

            if (pdtId != null && !pdtId.isEmpty()) {
                tCompeteTender.setPdtId(pdtId);
            }
            if (price != null && !price.isEmpty()) {
                tCompeteTender.setPrice(new BigDecimal(price));
            }
            if (weight != null && !weight.isEmpty()) {
                tCompeteTender.setWeight(new BigDecimal(weight));
            }
            if (winBidPrice != null && !winBidPrice.isEmpty()) {
                if (winBidPrice.equals("*")) {
                    //如果是*，则通过id查询出price
                    tCompeteTender.setWinBidPrice(tCompeteTender.getPrice());
                } else {
                    tCompeteTender.setWinBidPrice(new BigDecimal(winBidPrice));
                }
            }
            if (winBidWeight.equals("*")) {
                //如果是*，则通过id查询出weight
                return SzResult.Error("中标总量不能为*");
            }
// tCompeteTender.setWinBidWeight
            //        先查出中了哪些标
            QueryWrapper<TCompeteTender> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("COMPETE_ID", tCompeteTender.getCompeteId());
            queryWrapper3.eq("DEL_FLAG", 0);
            queryWrapper3.eq("WIN_BID",1);
            queryWrapper3.eq("PDT_ID", tCompeteTender.getPdtId());
            //        先按照价格
            queryWrapper3.orderByDesc("PRICE")
                    .orderByDesc("WEIGHT") // 价格相同的情况下按天数降序
                    .orderByAsc("CREATE_TIME"); // 价格和天数都相同的情况下按创建时间升序
            List<TCompeteTender> competeTenders = tCompeteTenderService.list(queryWrapper3);
            // 计算已分配的总重量
            BigDecimal executeWeight = BigDecimal.ZERO;
            for (TCompeteTender competeTender : competeTenders) {
                executeWeight = executeWeight.add(competeTender.getWeight());
            }

// 查询品种总重量
            QueryWrapper<TCompeteDetail> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("COMPETE_ID", tCompeteTender.getCompeteId());
            queryWrapper2.eq("DEL_FLAG", 0);
            queryWrapper2.eq("DATA_FROM", tCompeteTender.getDataFrom());
            queryWrapper2.eq("PDT_ID", tCompeteTender.getPdtId());
            TCompeteDetail competeDetail = tCompeteDetailService.getOne(queryWrapper2);
            BigDecimal weight3 = competeDetail.getPdtWeight();

// 计算剩余可分配量
            BigDecimal remainingWeight = weight3.subtract(executeWeight);

// 请求分配的重量（示例中假设从map中获取，实际情况请根据需求调整）
            BigDecimal requestWeight = tCompeteTender.getWeight();

// 确保请求分配的重量不超过剩余可分配量
            BigDecimal Weight = requestWeight.min(remainingWeight);

            if ( Weight.compareTo(BigDecimal.ZERO) <= 0) {
                // 如果没有剩余或请求重量无效，设置错误消息
                return SzResult.Error("确认中标失败,已经使用完量了或请求重量不合法");
            } else {
                // 更新WIN_BID_WEIGHT为实际可分配的最大量
                tCompeteTender.setWinBidWeight(Weight);
            }
            tCompeteTender.setWinBid(String.valueOf(1));
            tCompeteTender.setCompeteAuditTime(LocalDateTime.now());
//        tCompeteTender.setCreateTime(LocalDateTime.now());
            SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
            tCompeteTender.setCompeteAuditor(user.getId());
            tCompeteTender.setCompeteAuditorName(user.getTrueName());
            tCompeteTenderService.updateById(tCompeteTender);
        } else {
            return SzResult.Error("未开标,不能修改");
        }

        return SzResult.Success();
    }

    //查询竞标结果
    public SzResult getCompeteResult(String page, String pageSize, String competeId, String pdtId, String cpyId, String winBid, String sortStatus, String winBidStauts,String plantId) {
        long total = 0;
        Map<String, Object> map = new HashMap<>();
        List<TCompeteTender> records;
        if (page == null || page.equals("")) {
            QueryWrapper<TCompeteTender> tCompeteTenderQueryWrapper = new QueryWrapper<>();
            tCompeteTenderQueryWrapper.eq(competeId != null && !competeId.equals(""), "COMPETE_ID", competeId);
            tCompeteTenderQueryWrapper.eq(pdtId != null && !pdtId.equals(""), "PDT_ID", pdtId);
            tCompeteTenderQueryWrapper.eq(cpyId != null && !cpyId.equals(""), "CPY_ID", cpyId);
            tCompeteTenderQueryWrapper.eq(winBid != null && !winBid.equals(""), "WIN_BID", winBid);
            tCompeteTenderQueryWrapper.eq("DEL_FLAG", 0);
            tCompeteTenderQueryWrapper.orderByDesc("CREATE_TIME");
            tCompeteTenderQueryWrapper.eq("DATA_FROM", plantId);
            records = tCompeteTenderService.list(tCompeteTenderQueryWrapper);
        } else {
            Page<TCompeteTender> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
            QueryWrapper<TCompeteTender> tCompeteTenderQueryWrapper = new QueryWrapper<>();
//        tCompeteTenderQueryWrapper.eq(id != null && !id.equals(""), "ID", id);
            tCompeteTenderQueryWrapper.eq(competeId != null && !competeId.equals(""), "COMPETE_ID", competeId);
            tCompeteTenderQueryWrapper.eq(pdtId != null && !pdtId.equals(""), "PDT_ID", pdtId);
            tCompeteTenderQueryWrapper.eq(cpyId != null && !cpyId.equals(""), "CPY_ID", cpyId);
            tCompeteTenderQueryWrapper.eq("DATA_FROM", plantId);
            if (winBid != null && !winBid.equals("")) {
                if (winBid.equals("0")) {
                    tCompeteTenderQueryWrapper.and(i -> i.eq("WIN_BID", winBid).or().isNull("WIN_BID"));
                } else {
                    tCompeteTenderQueryWrapper.eq("WIN_BID", winBid);
                }
            }
//            if (winBidStauts.equals("1")) {//未开标,只查未开标的competeId
//                QueryWrapper<TCompete> tCompeteQueryWrapper = new QueryWrapper<>();
//                tCompeteQueryWrapper.eq("ID", competeId);
//                tCompeteQueryWrapper.lt("STATUS", 31);
//                TCompete one = competeService.getOne(tCompeteQueryWrapper);
//                if (one != null) {
//                    tCompeteTenderQueryWrapper.eq(competeId != null && !competeId.equals(""), "COMPETE_ID", competeId);
//                }
//            }
            tCompeteTenderQueryWrapper.eq("DEL_FLAG", 0);

            if (sortStatus != null && !sortStatus.isEmpty()) {
                if (sortStatus.equals("priceasc")) {
                    tCompeteTenderQueryWrapper.orderByAsc("PRICE");
                }
                if (sortStatus.equals("pricedesc")) {
                    tCompeteTenderQueryWrapper.orderByDesc("PRICE");
                }
                if (sortStatus.equals("weightasc")) {
                    tCompeteTenderQueryWrapper.orderByAsc("WEIGHT");
                }
                if (sortStatus.equals("weightdesc")) {
                    tCompeteTenderQueryWrapper.orderByDesc("WEIGHT");
                }
            }
            tCompeteTenderQueryWrapper.orderByDesc("CREATE_TIME");
            IPage<TCompeteTender> competeList = tCompeteTenderService.page(page1, tCompeteTenderQueryWrapper);
            //将competeList转换成GetCompeteTenderVo
            records = competeList.getRecords();
            total = competeList.getTotal();
        }


        List<GetCompeteTenderVo> getCompeteTenderVos = new ArrayList<>();
        List<GetCompeteTenderVo> invisibleVos = new ArrayList<>();
        List<GetCompeteTenderVo> trueVos = new ArrayList<>();

        for (TCompeteTender record : records) {
            GetCompeteTenderVo getCompeteTenderVo = new GetCompeteTenderVo();
            getCompeteTenderVo.setCompeteId(record.getCompeteId());//竞标ID

            getCompeteTenderVo.setPdtId(record.getPdtId());//产品ID
            TCompete tCompete = competeService.getById(record.getCompeteId());
            getCompeteTenderVo.setCompeteTitle(tCompete.getTitle());
            getCompeteTenderVo.setBidType(tCompete.getBidType() == 1 ? "车数" : "吨数");
            try {
                getCompeteTenderVo.setPdtName(iCProductsInfoService.getById(record.getPdtId()).getPdtinfPdt());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //如果没到开标时间，价格和重量不显示
            if (tCompete.getBeginDate().isBefore(LocalDateTime.now()) && tCompete.getStatus() > 40) {
                getCompeteTenderVo.setPrice(record.getPrice() != null ? String.valueOf(record.getPrice()) : " ");//价格
                getCompeteTenderVo.setWeight(record.getWeight() != null ? String.valueOf(record.getWeight()) : " ");//重量
            } else {
                getCompeteTenderVo.setPrice("*");//价格
                getCompeteTenderVo.setWeight("*");//重量
            }
//            getCompeteTenderVo.setPrice(String.valueOf(record.getPrice()));//价格
//            getCompeteTenderVo.setWeight(String.valueOf(record.getWeight()));//重量
            getCompeteTenderVo.setCpyId(record.getCpyId());//公司ID
            try {
                CCompanys cCompanys = companysService.getById(record.getCpyId());
                getCompeteTenderVo.setCpyName(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());
            } catch (Exception e) {
                e.printStackTrace();
            }
            getCompeteTenderVo.setCreateTime(String.valueOf(record.getCreateTime()));//创建时间
            getCompeteTenderVo.setWinBidPrice(record.getPrice() != null ? String.valueOf(record.getWinBidPrice()) : " ");//中标价格
            getCompeteTenderVo.setWinBidWight(record.getWeight() != null ? String.valueOf(record.getWinBidWeight()) : " ");//中标重量
            getCompeteTenderVo.setWinBid(String.valueOf(record.getWinBid()));//是否中标

            getCompeteTenderVo.setBidDay(record.getBidDay());
            getCompeteTenderVo.setCompeteAuditor(record.getCompeteAuditor());//竞标审核人
            getCompeteTenderVo.setCompeteAuditTime(String.valueOf(record.getCompeteAuditTime()));//定标时间
            getCompeteTenderVo.setId(record.getId());
            getCompeteTenderVo.setCompeteAuditor(record.getCompeteAuditor());
            getCompeteTenderVo.setCompeteAuditorName(record.getCompeteAuditorName());
            QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
            sysFilesQueryWrapper.eq("CONN_ID", record.getId());
            List<SysFiles> fileList = fileBu.list(sysFilesQueryWrapper);
            getCompeteTenderVo.setFileList(fileList);
            if (getCompeteTenderVo.getPrice() != null && !getCompeteTenderVo.getPrice().equals("*") && getCompeteTenderVo.getWeight() != null && !getCompeteTenderVo.getWeight().equals("*")) {
                getCompeteTenderVos.add(getCompeteTenderVo);
            } else {
                invisibleVos.add(getCompeteTenderVo);
            }

        }
        Collections.shuffle(invisibleVos);
        //将invisibleVos中的元素添加到trueVos里面,然后再将getCompeteTenderVos中的元素添加到trueVos里面
        trueVos.addAll(invisibleVos);
        trueVos.addAll(getCompeteTenderVos);
        map.put("total", total);
        map.put("list", trueVos);
        return SzResult.success(map);
    }


    /**
     * 竞标结果详情
     */
    public SzResult competeResultDetail(String id,String plantId) {
        QueryWrapper<TCompeteTender> tCompeteTenderQueryWrapper = new QueryWrapper<>();
        tCompeteTenderQueryWrapper.eq("ID", id);
        tCompeteTenderQueryWrapper.eq("DEL_FLAG", 0);
        tCompeteTenderQueryWrapper.eq("DATA_FROM", plantId);
        TCompeteTender tCompeteTender = tCompeteTenderService.getOne(tCompeteTenderQueryWrapper);
        if (tCompeteTender == null) {
            return SzResult.error("竞标结果不存在");
        }
        GetCompeteTenderVo getCompeteTenderVos = new GetCompeteTenderVo();
        getCompeteTenderVos.setCompeteId(tCompeteTender.getCompeteId());//竞标ID
        getCompeteTenderVos.setPdtId(tCompeteTender.getPdtId());//产品ID
        getCompeteTenderVos.setCompeteTitle(competeService.getById(tCompeteTender.getCompeteId()).getTitle());
        try {
            getCompeteTenderVos.setPdtName(iCProductsInfoService.getById(tCompeteTender.getPdtId()).getPdtinfPdt());
        } catch (Exception e) {
            e.printStackTrace();
        }
        getCompeteTenderVos.setPrice(String.valueOf(tCompeteTender.getPrice()));//价格
        getCompeteTenderVos.setWeight(String.valueOf(tCompeteTender.getWeight()));//重量
        getCompeteTenderVos.setCpyId(tCompeteTender.getCpyId());//公司ID
        try {
            CCompanys cCompanys = companysService.getById(tCompeteTender.getCpyId());
            getCompeteTenderVos.setCpyName(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());
        } catch (Exception e) {
            e.printStackTrace();
        }
        getCompeteTenderVos.setCreateTime(String.valueOf(tCompeteTender.getCreateTime()));//创建时间
        getCompeteTenderVos.setWinBidPrice(String.valueOf(tCompeteTender.getWinBidPrice()));//中标价格
        getCompeteTenderVos.setWinBidWight(String.valueOf(tCompeteTender.getWinBidWeight()));//中标重量
        getCompeteTenderVos.setWinBid(String.valueOf(tCompeteTender.getWinBid()));//是否中标
        getCompeteTenderVos.setCompeteAuditor(tCompeteTender.getCompeteAuditor());//竞标审核人
        getCompeteTenderVos.setCompeteAuditTime(String.valueOf(tCompeteTender.getCompeteAuditTime()));//定标时间
        getCompeteTenderVos.setId(tCompeteTender.getId());
        getCompeteTenderVos.setCompeteAuditor(tCompeteTender.getCompeteAuditor());


        QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
        sysFilesQueryWrapper.eq("CONN_ID", id);
        List<SysFiles> fileList = fileBu.list(sysFilesQueryWrapper);
        getCompeteTenderVos.setFileList(fileList);
        return SzResult.success(getCompeteTenderVos);

    }


    //上传文件
    public SzResult uploadFile(MultipartFile file, String connId, String token) throws Exception {
//    fileName去掉type
        String fileName = file.getOriginalFilename();
//        绝对文件名
        String absoluteFileName = fileName.substring(0, fileName.lastIndexOf("."));
//        fileType
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + suffix;
//        项目路径下的upload文件夹
        File upload = new File("upload");
        if (!upload.exists()) {
            upload.mkdirs();
        }
// 获取当前年份和月份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String currentMonth = LocalDateTime.now().format(formatter);
// 创建以月份为名的文件夹
        File monthFolder = new File(upload.getAbsolutePath() + File.separator + currentMonth);

        if (!monthFolder.exists()) {
            monthFolder.mkdirs();
        }
// 设置文件存放的路径
        String filePath = monthFolder.getAbsolutePath() + File.separator;

        File dest = new File(filePath + newFileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        SysFiles sysFiles = new SysFiles();
        sysFiles.setId(uuid);
        sysFiles.setConnId(connId);
        sysFiles.setUploadFrom(StpUtil.getLoginIdByToken(token).toString());
        sysFiles.setFileName(fileName);
        sysFiles.setFilePath(filePath);
        sysFiles.setFileSize(String.valueOf(file.getSize()));
        sysFiles.setFileType(suffix.replace(".", ""));
        sysFiles.setUploadTime(LocalDateTime.now());
        fileBu.save(sysFiles);
        return SzResult.success(sysFiles);
    }

    //    下载文件
    public SysFiles downloadFile(String id) {
//        根据id区数据库中查询文件信息
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        return sysFiles;
    }

    //    删除文件
    public SzResult deleteFile(String fileId) {
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", fileId);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        String filePath = sysFiles.getFilePath();
        String fileType = sysFiles.getFileType();
        File file = new File(filePath + sysFiles.getId() + "." + fileType);
        if (file.exists()) {
            file.delete();
        }
        fileBu.removeById(fileId);
        return SzResult.Success();
    }

    //    文件预览
    public Path previewFile(String fileId) {
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", fileId);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        //        判断一下sysFiles.getFileType()是否是图片格式
        if (sysFiles.getFileType().equals("jpg") || sysFiles.getFileType().equals("png") || sysFiles.getFileType().equals("gif") || sysFiles.getFileType().equals("jpeg") || sysFiles.getFileType().equals("bmp") || sysFiles.getFileType().equals("webp") || sysFiles.getFileType().equals("svg")) {
            String filePath = sysFiles.getFilePath();
            String fileType = sysFiles.getFileType();
            Path path = Paths.get(filePath + sysFiles.getId() + "." + fileType);
            return path;
        } else {
            return null;
        }
    }

    @Async
    public Future<List<CompeteTenderExcelEn>> exportExcel(List<Map<String, Object>> fields, List<Map<String, Object>> ids, String filename,
                                                          boolean isHeader, String mode, Boolean original, Map<String, String> pager, Map<String, String> form, String sheetName, HttpServletResponse response, String token) {
        List<Map<String, Object>> newIds = new ArrayList<>();
        List<CompeteTenderExcelEn> competeTenderExcelEns = new ArrayList<>();//最终数据
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            Object object = field.get("field");
                            if (id.containsKey(object)) {
                                newId.put(object.toString(), id.get(object));
                            }
                        }
                        newIds.add(newId);
                    }
                    for (Map<String, Object> newId : newIds) {
                        CompeteTenderExcelEn tenderExcelEn = CompeteTenderExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            String key = entry.getKey();
                            if (key.equals("competeTitle")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setTitle(entry.getValue().toString());
                                }
                            }
                            if (key.equals("pdtName")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setPdtInfPdt(entry.getValue().toString());
                                }
                            }
                            if (key.equals("price")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setPrice(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (key.equals("bidType")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setBidType(entry.getValue().toString().equals("1 ") ? "车数" : "吨数" );
                                }
                            }
                            if (key.equals("weight")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setWeight(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                            bidDay
                            if (key.equals("bidDay")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setBidDay(entry.getValue().toString());
                                }
                            }
                            if (key.equals("cpyName")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCpyCo(entry.getValue().toString());
                                }
                            }
                            if (key.equals("createTime")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCreatTime(entry.getValue().toString().replace("T"," "));
                                }
                            }
                            if (key.equals("winBidPrice")) {
                                if (entry.getValue() != null) {
                                    String value = Objects.toString(entry.getValue(), null);
                                    if (value.equals("null")) {
                                        tenderExcelEn.setWinBidPrice(null);
                                    } else {
                                        tenderExcelEn.setWinBidPrice(new BigDecimal(value));
                                    }
                                }
                            }
                            if (key.equals("winBidWight")) {
                                if (entry.getValue() != null) {
                                    String value = Objects.toString(entry.getValue(), null);
                                    if (value.equals("null")) {
                                        tenderExcelEn.setWinBidWeight(null);
                                    } else {
                                        tenderExcelEn.setWinBidWeight(new BigDecimal(value));
                                    }
                                }
                            }
                            if (key.equals("winBid")) {
                                if (entry.getValue() != null) {
                                    String winBid1 = entry.getValue().toString();
                                    switch (winBid1) {
                                        case "1":
                                            winBid1 = "中标";
                                            break;
                                        case "2":
                                            winBid1 = "未中标";
                                            break;
                                        case "0":
                                        case "":
                                        case "null":
                                            winBid1 = "未审";
                                            break;
                                    }
                                    tenderExcelEn.setWinBid(winBid1);
                                }
                            }
                            if (key.equals("competeAuditorName")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCompeteAuditorName(entry.getValue().toString());
                                }
                            }
                            if (key.equals("competeAuditTime")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCompeteAuditTime(entry.getValue().toString().replace("T"," "));
                                }
                            }
                        }
                        competeTenderExcelEns.add(tenderExcelEn);
                    }
                    break;
                case "all":
                    String pdtId = form.get("pdtId");
                    String competeId = form.get("competeId");
                    String winBid = form.get("winBid");
                    QueryWrapper<TCompeteTender> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("DEL_FLAG", 0);
                    queryWrapper.eq(pdtId != null && !pdtId.equals(""), "PDT_ID", pdtId);
                    queryWrapper.eq(competeId != null && !competeId.equals(""), "COMPETE_ID", competeId);
                    queryWrapper.eq(winBid != null && !winBid.equals(""), "WIN_BID", winBid);
                    queryWrapper.orderByDesc("PDT_ID","WIN_BID_PRICE","WIN_BID_WEIGHT","CREATE_TIME");
                    List<TCompeteTender> tCompeteTenders = tCompeteTenderService.list(queryWrapper);
                    for (TCompeteTender tCompeteTender : tCompeteTenders) {
                        String competeId1 = tCompeteTender.getCompeteId();
                        String winBid1 = tCompeteTender.getWinBid();
                        switch (winBid1) {
                            case "1":
                                winBid1 = "中标";
                                break;
                            case "2":
                                winBid1 = "未中标";
                                break;
                            case "0":
                            case "":
                            case "null":
                                winBid1 = "未审";
                                break;
                        }
                        TCompete compete = competeService.getById(competeId1);
                        CCompanys companys = companysService.getById(tCompeteTender.getCpyId());
                        String competeAuditorName1 = "";
                        if (compete.getAuditorId() !=null && !compete.getAuditorId().equals("")){
                            competeAuditorName1 = iSysUserService.getById(compete.getAuditorId()).getTrueName();
                        }
                        CompeteTenderExcelEn competeTenderExcelEn = CompeteTenderExcelEn.builder()
                                .title(Optional.ofNullable(compete.getTitle()).map(Object::toString).orElse(""))
                                .pdtInfPdt(Optional.ofNullable(iCProductsInfoService.getById(tCompeteTender.getPdtId()).getPdtinfPdt()).map(Object::toString).orElse(""))
                                .price(tCompeteTender.getPrice())
                                .weight(tCompeteTender.getWeight())
                                .cpyCo(Optional.of(companys.getCpyCo()+"."+companys.getCpyChico()).map(Object::toString).orElse(""))
                                .creatTime(Optional.ofNullable(tCompeteTender.getCreateTime()).map(Object::toString).orElse("").replace("T"," "))
                                .winBidWeight(tCompeteTender.getWinBidWeight())
                                .winBidPrice(tCompeteTender.getWinBidPrice())
                                .winBid(Optional.of(winBid1).map(Object::toString).orElse(""))
                                .competeAuditorName(Optional.ofNullable(tCompeteTender.getCompeteAuditorName()).map(Object::toString).orElse(""))
                                .competeAuditTime(Optional.ofNullable(tCompeteTender.getCompeteAuditTime()).map(Object::toString).orElse("").replace("T"," "))
                                .bidType(compete.getBidType() == 1 ? "车数" : "吨数")
                                .bidDay(tCompeteTender.getBidDay().toString().substring(0, 10))
                                .competeAuditorName1(competeAuditorName1)
//                                .competeAuditTime1(compete.getAuditTime().toString().replace("T"," "))
                                .competeAuditTime1(Optional.ofNullable(compete.getAuditTime()).map(Object::toString).orElse("").replace("T"," "))
                                .build();
                        if (compete.getTitle().contains("打包")){
                            competeTenderExcelEn.setBidDay(compete.getExecuteStartTime().substring(0, 10)+"~"+compete.getExecuteEndTime().substring(0, 10));
                        }
                        competeTenderExcelEns.add(competeTenderExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
                    for (Map<String, Object> newId : newIds) {
                        CompeteTenderExcelEn tenderExcelEn = CompeteTenderExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            String key = entry.getKey();
                            if (key.equals("title")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setTitle(entry.getValue().toString());
                                }
                            }
                            if (key.equals("pdtInfPdt")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setPdtInfPdt(entry.getValue().toString());
                                }
                            }
                            if (key.equals("price")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setPrice(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (key.equals("bidType")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setBidType(entry.getValue().toString().equals("1 ") ? "车数" : "吨数" );
                                }
                            }
                            if (key.equals("weight")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setWeight(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            //                            bidDay
                            if (key.equals("bidDay")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setBidDay(entry.getValue().toString());
                                }
                            }
                            if (key.equals("cpyCo")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCpyCo(entry.getValue().toString());
                                }
                            }
                            if (key.equals("createTime")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCreatTime(entry.getValue().toString().replace("T"," "));
                                }
                            }
                            if (key.equals("winBidPrice")) {
                                if (entry.getValue() != null) {
                                    String value = Objects.toString(entry.getValue(), null);
                                    if (value.equals("null")) {
                                        tenderExcelEn.setWinBidPrice(null);
                                    } else {
                                        tenderExcelEn.setWinBidPrice(new BigDecimal(value));
                                    }
                                }
                            }
                            if (key.equals("winBidWeight")) {
                                if (entry.getValue() != null) {
                                    String value = Objects.toString(entry.getValue(), null);
                                    if (value.equals("null")) {
                                        tenderExcelEn.setWinBidWeight(null);
                                    } else {
                                        tenderExcelEn.setWinBidWeight(new BigDecimal(value));
                                    }
                                }
                            }
                            if (key.equals("winBid")) {
                                if (entry.getValue() != null) {
                                    String winBid1 = entry.getValue().toString();
                                    switch (winBid1) {
                                        case "1":
                                            winBid1 = "中标";
                                            break;
                                        case "2":
                                            winBid1 = "未中标";
                                            break;
                                        case "0":
                                        case "":
                                        case "null":
                                            winBid1 = "未审";
                                            break;
                                    }
                                    tenderExcelEn.setWinBid(winBid1);
                                }
                            }
                            if (key.equals("competeAuditorName")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCompeteAuditorName(entry.getValue().toString());
                                }
                            }
                            if (key.equals("competeAuditTime")) {
                                if (entry.getValue() != null) {
                                    tenderExcelEn.setCompeteAuditTime(entry.getValue().toString());
                                }
                            }
                        }
                        competeTenderExcelEns.add(tenderExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(competeTenderExcelEns);
    }


}
